package com.abel.quiz.security;/**
 * Created by abel.lin on 2017/8/4.
 */
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.abel.quiz.common.Constants;
import com.abel.quiz.common.ContextUtil;
import com.abel.quiz.po.AuthRolePo;
import com.abel.quiz.po.UserInfoPo;
import com.abel.quiz.services.AuthRoleService;
import com.abel.quiz.services.UserInfoService;
import com.abel.quiz.vo.UserInfoDomain;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
/**
 * @author abel.lin
 * @date_time 2017/8/4 14:40
 * @description
 */
public class AdminUserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private UserInfoService userService;
    @Autowired
    AuthRoleService roleService;

    //登录验证
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UserInfoPo user = userService.selectByLoginName(username);

        if(user==null){
            ContextUtil.setRequestAttr(Constants.loginCode,Constants.LoginErrorCode.userNotExists);
            throw new UsernameNotFoundException("member "+username +" not found.");
        }

        UserInfoDomain userDomain = UserInfoDomain.genDomain(user);
        Set<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(user);
        userDomain.setAuthorities(grantedAuths);

        //封装成spring security的user
//        User userdetail = new User(user.getLoginName(), user.getLoginPwd(),
//                (user.getEnabled() != null && user.getEnabled()==1), // 账号状态 0 表示停用 1表示启用
//                true, true, true, grantedAuths // 用户的权限
//        );
        return userDomain;
    }

    //取得用户的权限
    private Set<GrantedAuthority> obtionGrantedAuthorities(UserInfoPo member) {

        Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();

        List<AuthRolePo> roles = roleService.selectByUserId(member.getId());
        if(roles!=null){
            for(AuthRolePo role : roles) {
                authSet.add(new SimpleGrantedAuthority(role.getRoleCode().trim()));
            }
        }

        return authSet;
    }

}